﻿/*******公用函数 by linder sdata007@163.com 2012-05-13*******/
window["huaba"]=window["huaba"] || {};
//获取路径目录
huaba.path = {
    //服务端根目录
    ServerPath: 'http://192.168.0.107/api/', 
    //获取客户端根目录
    ClientPath: function(){
		var strFullPath=window.document.location.href;
			var strPath=window.document.location.pathname;
			var pos=strFullPath.indexOf(strPath);
			var prePath=strFullPath.substring(0,pos);
			var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
			return (prePath+postPath);
	}
};
//核心函数
huaba.core = {
	//版本号
	version:"20120513",
	//获取随机数
	getRandom:function(){
		return "t"+new Date().getTime()+Math.round(Math.random()*10000);
	},
	//类型判断
	type:function(o){   
		var t=Object.prototype.toString.call(o),l=t.length;
			return o==null?String(o):t.slice(8,l-1);
	},
	//转换unicode编码
	toUnicode:function(str){
		var a=[],i=0;
		for (;i<str.length;){
			a[i]=("00"+str.charCodeAt(i++).toString(16)).slice(-4);
		}
		return "\\u"+a.join("\\u");
	},
	//转换unicode反编码
	unUnicode:function(str){
		return unescape(str.replace(/\\/g, "%"))
	},
	//支持单字节和双字节判断的字符串截取
	substr:function(str,len){
		if(!str || !len){return'';}
		//预期计数：中文2字节，英文1字节
		var a=0;
		//循环计数
		var i=0;
		//临时字串
		var temp='';
		for(i=0;i<str.length;i++){
			if(str.charCodeAt(i)>255){
				//按照预期计数增加2
				a+=2;
			}else{
				a++;
			}
			//如果增加计数后长度大于限定长度，就直接返回临时字符串
			if(a>len){return temp+'...';}
			//将当前内容加到临时字符串
			temp+=str.charAt(i);
		}
		//如果全部是单字节字符，就直接返回源字符串
		return str;
	},
	//url添加参数
	addUrlParams:function(key,val,url){
		var strurl=url || window.document.location.href;
		if(strurl.indexOf("?")<0){
			return strurl+"?"+key+"="+val;
		}else{
			var laststr=strurl.slice(-1);
			if(laststr=="&"){
				return strurl+key+"="+val;
			}else{
				return strurl+"&"+key+"="+val;
			}
		}
	},
	//url参数设置
	setUrlParams:function(key,val,url){
		var strurl=url || window.document.location.href;
		//return strurl.replace(new RegExp(key+"=[^&]*(&{0,1})","ig"),key+"="+val+"$1");
		//url清理
		strurl=strurl.replace(new RegExp("([\&|\?])"+key+"=[^&]*(&{0,1})","ig"),"$1");
		strurl=strurl.replace(/#.*/gi,"");
		if(val==null){
			return strurl;
		}else{
			//添加
			return huaba.fun.addUrlParams(key,encodeURIComponent(val),strurl);
		}
	},
	//url参数获取
	getUrlParams:function(key,url){
		var strurl=url || window.document.location.href;
		var vals=new RegExp("[\&|\?]"+key+"=([^&]*)&{0,1}","ig").exec(strurl);
		return vals?decodeURIComponent(vals[1].replace(/#.*/gi,"")):"";
	},
	//对象属性检查
	objAttrCheck:function(o,attr){
		if(!o){
			return false;
		}else if(attr){
			var attrs=attr.split(",");
			var flag=false;
			for(var i=0,len=attrs.length;i<len;i++){
				var attrs2=attrs[i].split(".");
				for(var i2=0,len2=attrs2.length;i2<len2;i2++){
					attrs2[i2]='["'+attrs2[i2]+'"]';
				}
				try{
					var temp=eval("o"+attrs2.join(""));
					if(typeof temp=="undefined"){
						flag=false;
					}else{
						flag=true;
					}
				}
				catch(e){
					flag=false;
					break;
				}
			}
			return flag;
		}
		return true;
	}	
};
huaba.fun = {
	getJson:function(url,cb,stateBox,stateBox2){
		$.getJSON(url,function(data){
			cb(data);
		});
	},
	daysBetween:function(DateOne,DateTwo) 
		{       
		var OneMonth = DateOne.substring(5,DateOne.lastIndexOf ('-'));      
		var OneDay = DateOne.substring(DateOne.length,DateOne.lastIndexOf ('-')+1);      
		var OneYear = DateOne.substring(0,DateOne.indexOf ('-'));         
		var TwoMonth = DateTwo.substring(5,DateTwo.lastIndexOf ('-'));      
		var TwoDay = DateTwo.substring(DateTwo.length,DateTwo.lastIndexOf ('-')+1);      
		var TwoYear = DateTwo.substring(0,DateTwo.indexOf ('-'));         
		var cha=((Date.parse(OneMonth+'/'+OneDay+'/'+OneYear)- Date.parse(TwoMonth+'/'+TwoDay+'/'+TwoYear))/86400000);       
		return Math.abs(cha);  
	},
	//自定义序列化表单值
	serialize:function(formId,type){
		var i,j,form,q=[];
		if(!formId){
			return;
		}
		form= document.getElementById(formId);
		if(form.nodeName!=="FORM"){
			return;
		}
		switch(type){
			case"1":
				for(i=0; i<form.elements.length; i++){
					if(form.elements[i].name===""|| form.elements[i].disabled === true){
						continue;
					}
					var fltName = form.elements[i].name;
					switch(form.elements[i].nodeName){
						case"INPUT":
							switch(form.elements[i].type){
								case"text":
								case"hidden":
								case"submit":
									if(fltName.substring(0,3)!="flt"){
										q.push(form.elements[i].name + "=" + encodeURIComponent(form.elements[i].value));//encodeURIComponent转义特殊字符
									}
									break;
								case"password":
									if(fltName.substring(0,3)!="flt"){
										q.push(form.elements[i].name + "=" + hex_md5(encodeURIComponent(form.elements[i].value)));
									}
									break;
								case"checkbox":
								case"radio":
									if(form.elements[i].checked){
										q.push(form.elements[i].name+"=" + encodeURIComponent(form.elements[i].value));
									}
									break;
								case"file":
									break;
							}
							break;
						case"TEXTAREA":
							q.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].value));
							break;
						case"SELECT":
							switch(form.elements[i].type){
								case"select-one":
									q.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].value));
									break;
								case"select-multiple":
									for(j=0;j<form.elements[i].options.length;j++){
										if(form.elements[i].options[j].selected){
											q.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].options[j].value));
										}
									}
									break;
							}
							break;
						case"BUTTON":
							switch(form.elements[i].type){
								case"submit":
									q.push(form.elements[i].name+"="+encodeURIComponent(form.elements[i].value));
									break;
							}
							break;
					}
				}
				return q.join("&");
				break;
			case"2":
				for(i=0; i<form.elements.length; i++){
					if(form.elements[i].name===""|| form.elements[i].disabled === true){
						continue;
					}
					var fltName = form.elements[i].name;
					switch(form.elements[i].nodeName){
						case"INPUT":
							switch(form.elements[i].type){
								case"text":
								case"hidden":
								case"submit":
									if(fltName.substring(0,3)!="flt"){
										q.push(form.elements[i].value);
									}
									break;
								case"password":
									if(fltName.substring(0,3)!="flt"){
										q.push(hex_md5(encodeURIComponent(form.elements[i].value)));
									}
									break;
								case"checkbox":
								case"radio":
									if(form.elements[i].checked){
										q.push(form.elements[i].value);
									}
									break;
								case"file":
									break;
							}
							break;
						case"TEXTAREA":
							q.push(form.elements[i].value);
							break;
						case"SELECT":
							switch(form.elements[i].type){
								case"select-one":
									q.push(form.elements[i].value);
									break;
								case"select-multiple":
									for(j=0;j<form.elements[i].options.length;j++){
										if(form.elements[i].options[j].selected){
											q.push(form.elements[i].options[j].value);
										}
									}
									break;
							}
							break;
						case"BUTTON":
							switch(form.elements[i].type){
								case"submit":
									q.push(form.elements[i].value);
									break;
							}
							break;
					}
				}
			return q.join("&");
			break;
		}
	},
	//基于jQuery的表单序列化到json对象
	paramStringToObj: function(serializedParams){
		var obj={};
		function evalThem (str) {
			var attributeName = str.split("=")[0];
			var attributeValue = str.split("=")[1];
			if(!attributeValue){
			return ;
		}
		var array = attributeName.split(".");
		for (var i = 1; i < array.length; i++) {
			var tmpArray = Array();
				tmpArray.push("obj");
			for (var j = 0; j < i; j++) {
				tmpArray.push(array[j]);
			};
		var evalString = tmpArray.join(".");
			if(!eval(evalString)){
				eval(evalString+"={};");
			}
		};
			eval("obj."+attributeName+"='"+attributeValue+"';");
		};
		var properties = serializedParams.split("&");
		for (var i = 0; i < properties.length; i++) {
			evalThem(properties[i]);
		};
		return obj;
	},
	//json对象转字符串
	ObjToStr: function(o) {
			if (o == undefined) {
				return "";
			}
			var r = [];
			if (typeof o == "string") return "\"" + o.replace(/([\"\\])/g, "\\$1").replace(/(\n)/g, "\\n").replace(/(\r)/g, "\\r").replace(/(\t)/g, "\\t") + "\"";
			if (typeof o == "object") {
				if (!o.sort) {
					for (var i in o)
						r.push("\"" + i + "\":" + huaba.fun.ObjToStr(o[i]));
					if (!!document.all && !/^\n?function\s*toString\(\)\s*\{\n?\s*\[native code\]\n?\s*\}\n?\s*$/.test(o.toString)) {
						r.push("toString:" + o.toString.toString());
					}
					r = "{" + r.join() + "}"
				} else {
					for (var i = 0; i < o.length; i++)
						r.push(huaba.fun.ObjToStr(o[i]))
					r = "[" + r.join() + "]";
				}
				return r;
			}
			return o.toString().replace(/\"\:/g, '":""');
	},
	//基于jQuery的表单序列化到json对象实例
	formToJson:function(){
		var serializedParams = this.serialize() + '&t='+ (new Date()).valueOf() + '&sign=' + hex_md5(this.params()+ '&' + (new Date()).valueOf());
		var obj = huaba.fun.paramString2obj(serializedParams);
		return huaba.fun.ObjToStr(obj);
	},
	
	// 获取URL参数
	Request: function(panStr, strUrl) {
		var  vStr="",sorStr=strUrl || location.href || document.location.href; 
		if(sorStr==null||sorStr==""||panStr==null||panStr=="")return vStr;  
		panStr+="="; 
		var itmp=sorStr.indexOf(panStr);  
		if(itmp<0){return vStr;}  
		sorStr=sorStr.substr(itmp+panStr.length);itmp=sorStr.indexOf("&");  
		if(itmp<0){return decodeURIComponent(sorStr);}else{sorStr=sorStr.substr(0,itmp);return decodeURIComponent(sorStr);} 
	},
	
	//获取客户端根目录
	baseUrl: function(){
		var strFullPath=window.document.location.href;
		var strPath=window.document.location.pathname;
		var pos=strFullPath.indexOf(strPath);
		var prePath=strFullPath.substring(0,pos);
		var postPath=strPath.substring(0,strPath.substr(1).indexOf('/')+1);
		return (prePath+postPath);
	},
	
	/*
		函数名：公用查询函数(ajax方式)
	*/
	fnAjax: function(oArg){
		opts = {
			url: oArg.sUrl || '',
			type: oArg.sType || 'GET',
			dataType: oArg.sDataType || 'json',
			data: oArg.oData || null,
			beforeSend: function(oXHR, oSettings){
				//ready
			},
            success: oArg.fnSuccess || function(oData){
                //ready
            },
			error: oArg.fnError || function(oXHR, sStatus){
                //ready
			},
			complete: oArg.fnComplete || function(oXHR, sStatus){
                //ready
			}
		};
		jQuery.ajax(opts);
	},

	/*
		函数名：公用提交表单
	*/
	fnSubmit: function(oArg){
		var opts = {}
		
		//提交设置
        arrPassword = [];
		opts = {
			beforeSerialize: function(){
                //清空文本框输入提示
		        /*$inputFontTip && $inputFontTip.each(function(){

					$(this).triggerHandler('focus');
				});*/
			},
			beforeSubmit: function(){
			},
			url: oArg.sUrl,
			dataType: "json",
			data: oArg.oData || null,
			success: function(oData){
                oArg.fnCallback && oArg.fnCallback(oData);
			},
			error: function(oXHR, sStatus){
                //ready
			},
            complete: function(oXHR, sStatus){
                //还原文本框输入提示
		        /*$inputFontTip && $inputFontTip.each(function(){
					$(this).triggerHandler('blur');
				});*/

			}
		};
		
		jQuery(oArg.elForm).ajaxSubmit(opts);
	},
	//类型判断
	type:function(o){   
		var t=Object.prototype.toString.call(o),l=t.length;
			return o==null?String(o):t.slice(8,l-1);
	},
	DataTable:function(opt){
			//定义配置
			var tbBox = opt.tbBox,//表格容器
				tbId = opt.tbId,//表格Id,用来绑定具体的表格
				tbColumn = opt.tbColumn,//表头标题
				tbData = opt.tbData;//表格数据或url
			var tbColLen = tbColumn.length,
				dLength = 0;
			var $tbBox = $("#" + tbBox);
			//加载数据
			var loadTbData = function(d){
				var tbData = d,
					tb_data_length = tbData.length;
				var arrTableHtml = [];
			//创建表格
			//表头
			arrTableHtml.push('<table border="0" cellspacing="0" cellpadding="0" class="netable">');
			arrTableHtml.push('<thead>');
			arrTableHtml.push('<tr>');
			$.each(tbColumn,function(i,val){
				arrTableHtml.push('<th key="'+(val.key || "")+'" class="netable_th" width="'+(val.width || '')+'">'+val.label+'</th>')
			});
			arrTableHtml.push('</tr>');
			arrTableHtml.push('</thead>');
			//表体
			arrTableHtml.push('<tbody>');
			//行
			$.each(tbData,function(i,o){
				//隔行换色
				var trClass="netable_odd"; 
				if(i%2) trClass="netable_event";
				arrTableHtml.push('<tr class="netable_body_tr ' + trClass + '">');
				for(var c=0;c<tbColLen;c++){
					//字段获取
					var key=tbColumn[c].key || "",txt=o[key] || "",formatter=tbColumn[c].formatter;
					if(formatter){txt=formatter(o,i) || "";}
					//数据填充
					arrTableHtml.push('<td class="netable_td netable_td_main"  width="'+(tbColumn[c].width || '')+'"><div class="netable_field">'+txt+'</div></td>');
				}
				arrTableHtml.push('</tr>');
			});
			arrTableHtml.push('</tbody>');
			arrTableHtml.push('</table>');
			$tbBox.html(arrTableHtml.join(""));
			var tr = $tbBox.find(".netable_body_tr"),
				td = $tbBox.find(".netable_td");
			tr.hover(function(){
				$(this).addClass("netable_hover");				  
			},function(){
				$(this).removeClass("netable_hover");	
			});
		};
		tbData && loadTbData(tbData);
		var _return={reloadData:loadTbData};
		return _return;
	},
	myPage: function(opt){
		var selfFn=arguments.callee;
		var pageBox = opt.pageBox,//分页容器
			totalRecord = opt.totalRecord,//总记录
			pageSize = opt.pageSize || 15,//分页大小
			pageIndex = opt.pageIndex || 1,//当前页面
			pageNum = opt.pageNum || 10,//显示标签数量
			totalPage=opt.totalPage || Math.ceil(totalRecord/pageSize),
			pageSpan = opt.pageSpan || "首页,上一页,{i},下一页,尾页",
			changePage=opt.changePage,
			callback=opt.callback;
			var pageSpanArry = pageSpan.split(",");
			if(pageIndex<0)pageIndex=1;
			if(pageIndex>totalPage)pageIndex=totalPage;
		var halfi=parseInt((pageNum-1)/2);
		var lefti=pageIndex-halfi;//左下标
		if(lefti<1)lefti=1;
		var righti=lefti+pageNum-1;//右下标
		if(righti>totalPage)righti=totalPage;
		var $pageBox=pageBox;
		if(huaba.fun.type(pageBox)=="String"){
			$pageBox=$("#"+pageBox);
		}
		//html组建
		var pageHtml=[];
		//查询结果
		pageHtml.push('<div class="dataPage">');
		pageHtml.push('<span class="dataPage_infor">查询结果：<span class="dadaPage_numfor">( '+pageIndex+' / '+totalPage+'页 共'+totalRecord+'条 每页'+pageSize+'条 )</span></span>');
		//首页，上一页
		if(pageIndex==1){
			pageHtml.push(' <span class="dataPage_btn_first dataPage_btn_off">'+pageSpanArry[0]+'</span> <span class="dataPage_btn_pre dataPage_btn_off">'+pageSpanArry[1]+'</span> ');
		}else{
			pageHtml.push(' <a href="#" class="dataPage_btn_first" page="1">'+pageSpanArry[0]+'</a> <a href="#" class="dataPage_btn_pre" page="'+(pageIndex-1)+'">'+pageSpanArry[1]+'</a> ');
		}
		//数字分页
		for(var i=lefti;i<=righti;i++){
			if(i==pageIndex){
				pageHtml.push('<span class="dataPage_num dataPage_num_on">'+pageSpanArry[2].replace("{i}",i)+'</span> ');
			}else{
				pageHtml.push('<a href="#" class="dataPage_num" page="'+i+'">'+pageSpanArry[2].replace("{i}",i)+'</a> ');
			}
		}
		//下一页，尾页
		if(pageIndex==totalPage){
			pageHtml.push(' <span class="dataPage_btn_next dataPage_btn_off">'+pageSpanArry[3]+'</span> <span class="dataPage_btn_last dataPage_btn_off">'+pageSpanArry[4]+'</span> ');
		}else{
			pageHtml.push(' <a href="#" class="dataPage_btn_next" page="'+(pageIndex+1)+'">'+pageSpanArry[3]+'</a> <a href="#" class="dataPage_btn_last" page="'+totalPage+'">'+pageSpanArry[4]+'</a> ');
		}
		//go
		pageHtml.push(' <input class="dataPage_goindex" type="text" value="跳转到" /> ');
		pageHtml.push('</div>');
		$pageBox.html(pageHtml.join(""));
		//a事件
		$pageBox.find("a").click(function(e){
			var num=parseInt($(this).attr("page")) || 0;
			if(num<1)num=1;
			if(num>totalPage)num=totalPage;
			opt.pageIndex=num;
			changePage(num);
			selfFn(opt);
			return false;
		});
		//go事件
		var goindex=$pageBox.find(".dataPage_goindex");
		goindex.click(function(e){
			var val=$(this).val();
			if(val=="跳转到" || val==""){
				$(this).val("");
			}
			if(!$(this).hasClass("dataPage_goindex_focus")){
				$(this).addClass("dataPage_goindex_focus");
			}
		});
		goindex.keydown(function(e){
			if(e.keyCode==13){//enter
				return false;
			}
		});
		goindex.keyup(function(e){
			if(e.keyCode==13){//enter
				var num=parseInt($(this).val()) || 0;
				if(num<1)num=1;
				if(num>totalPage)num=totalPage;
				opt.pageIndex=num;
				changePage(num);
				selfFn(opt);
				return false;
			}
		});
		callback && callback(pageIndex);
			
	},
	myDataTableExtend:function(opt){
		var $tableCon = $("#"+opt.tbBox);
		nd_global.dataBoxNull($tableCon);//空数据容器设置
		var tbData = opt.tbData;
		//创建空datatable对象
		var myDataTable =huaba.fun.DataTable($.extend(opt,{tbData:null}));
		if(huaba.fun.type(tbData)=="String"){//ajaxURL数据请求
			//数据获取
			var url=tbData;//获取url
			nd_global.getJson(url,function(r){
				myDataTable.reloadData(r);
				if(opt.isPage && r.pageNum>1){//分页
					if($("#page_"+opt.tbBox).size()<1){
						$tableCon.after('<div id="page_'+opt.tbBox+'"></div>');
					}
					$("#page_"+opt.tbBox).show();
					//分页调用
					huaba.fun.myPage({
						pageBox:'page_'+opt.tbBox,
						totalRecord:parseInt(r.totalRows),//总记录数
						pageSize:parseInt(r.pageRows),//分页大小
						pageIndex:parseInt(r.pageIndex),//当前页
						totalPage:parseInt(r.pageNum),//总分页数
						changePage:function(i){
							var urlpage = url;
								urlpage = huaba.core.setUrlParams("pageIndex",i,urlpage);
								urlpage = huaba.core.setUrlParams("totalRows",r.totalRows,urlpage);
								urlpage = huaba.core.setUrlParams("pageNum",r.pageNum,urlpage);
								urlpage = huaba.core.setUrlParams("offset",r.offset,urlpage);
								urlpage = huaba.core.setUrlParams("ids",r.ids,urlpage);
								nd_global.getJson(urlpage,function(d){
									myDataTable.reloadData(d.content);
								},$tableCon);
						}
					});
				}else{
					$("#page_"+opt.tbBox).empty();
					$("#page_"+opt.tbBox).hide();
				}
			},$tableCon,$("#page_"+opt.tbBox));
		}else{
			var page_size = opt.pageSize || 15
			var dlen = tbData.length;
			myDataTable.reloadData(tbData.slice(0,page_size));//加载数据
			if(opt.isPage && dlen>page_size){//分页
				if($("#page_"+opt.tbBox).size()<1){
					$tableCon.after('<div id="page_'+opt.tbBox+'"></div>');
				}
				$("#page_"+opt.tbBox).show();
				//分页调用
				huaba.fun.myPage({
					pageBox:'page_'+opt.tbBox,
					totalRecord:dlen,//总记录数
					pageSize:page_size,//分页大小
					pageIndex:1,//当前页
					changePage:function(i){
						myDataTable.reloadData(tbData.slice((i-1)*page_size,i*page_size));
					}
				});
			}else{
				$("#page_"+opt.tbBox).empty();
				$("#page_"+opt.tbBox).hide();
			}
		}
		return myDataTable;
	},
	//测试接口用
	json2list:function(o) {
	  if (huaba.fun.isFalse(o))  // 这个实际上只检查 [...], {...}, null
		return 'null'; // 如果是[],{}和null其中一个，就返回'null'字符
	  else {
		var i, s = '', t = huaba.fun.typeOf(o);
		for (i in o) {
		  var s1 = '', t1 = typeof o[i];
		  if (t1 === 'object')
			s1 = huaba.fun.json2list(o[i]);
		  else // 对于[...]及{...}以外的，直接字符化即可
			s1 = '<span>' + String(o[i]) + '</span>';
	
		  if (t === 'array')
			s += '<li>' + s1 + '</li>';
		  else //'object'需要加上键值
			s += '<li><span>' + i + '</span> : ' + s1 + '</li>';
		}
	  }
	  return '<ul>' + s + '</ul>';
	},
	//类型判断
	typeOf:function(value) {
	  var t = typeof value;
	  if (value === null)
		t = 'null'; //null表示什么都没有,只有null===null才返回true
	  if (t === 'object' && value.constructor === Array)
		t = 'array'; //如果type确实为'object'，后面才会执行
	  return t;
	},
	//验证json
	isFalse:function(value) {
	  var i, s = true, t = typeof value;
	  if (value !== null && t === 'object')
		for(i in value) return false; //如果对象是可枚举的
	  else if (t === 'function')
		return isFalse(value()); //依据函数的返回值判定
	  else
		s = value ? false : true;
	  return s;
	}
}
//浏览器判断
huaba.browser = {
	ie:function(s){
		if(!s)return !-[1,];
		switch(s){
			case 6:
			return !window.XMLHttpRequest;
			break;
			case 7:
			return !!window.ActiveXObject && window.XMLHttpRequest && !document.documentMode;
			case 8:
			return !!document.documentMode;	
		}
	},
	chrome:(-1!=navigator.userAgent.indexOf('Chrome/')),
	firefox:(-1!=navigator.userAgent.indexOf('Firefox')),
	safari:(-1!=navigator.userAgent.indexOf('Safari')),
	opera:(-1!=navigator.userAgent.indexOf('Opera'))
};



